package com.ctms.system.controller;

import com.ctms.common.utils.*;
import com.ctms.system.domain.*;
import com.ctms.system.service.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RequestMapping("/courseStudent")
@Controller
public class CourseStudentController {

    @Autowired
    CourseStudentService courseStudentService;
    @Autowired
    CourseService courseService;
    @Autowired
    CourseScoreService courseScoreService;
    @Autowired
    TaskReleaseService taskReleaseService;
    @Autowired
    UserService userService;
    @Autowired
    CorrectsTaskService correctsTaskService;

    //抽取公共方法
    private PageUtils comm(Map<String, Object> params,List<CourseDO> courseDOS) {
        Query query = new Query(params);
        //List<CourseDO> courseDOS =courseService.selectAllCourse(params);
        for (int i=0;i<courseDOS.size();i++){
            String teacherId=courseDOS.get(i).getCourseTeacher();
            String[] split=teacherId.split(",");
            String teacher="";
            for (int j=0;j<split.length;j++){
                String teacherName = courseService.getNameById(Integer.parseInt(split[j]));
                if (j != split.length-1){
                    teacher = teacher + teacherName + ",";
                }else {
                    teacher = teacher + teacherName;
                }
            }
            System.out.println(teacher);
            courseDOS.get(i).setCourseTeacher(teacher);
        }
        int total;
        total = courseService.count(query);
        PageUtils pageUtil = new PageUtils(courseDOS, total);
        return pageUtil;
    }

    @GetMapping("")
    public String courseStudent(Model model){
        //获取登录人对象
        UserDO userDO = ShiroUtils.getUser();
        model.addAttribute("user",userDO);
        return "sys/courseStudent/courseStudent";
    }

    @GetMapping("/list")
    @ResponseBody
    PageUtils list(@RequestParam Map<String, Object> params) {
        //获取登录人的身份
        UserDO userDO = ShiroUtils.getUser();
        int loginId=Integer.parseInt(Long.toString(userDO.getUserId()));
        params.put("loginId",loginId);
        // 查询列表数据
        Query query = new Query(params);
        List<CourseDO> courseDOS =courseStudentService.selectAllCourse(params);
        for (int i=0;i<courseDOS.size();i++){
            String teacherId=courseDOS.get(i).getCourseTeacher();
            String[] split=teacherId.split(",");
            String teacher="";
            for (int j=0;j<split.length;j++){
                String teacherName = courseService.getNameById(Integer.parseInt(split[j]));
                if (j != split.length-1){
                    teacher = teacher + teacherName + ",";
                }else {
                    teacher = teacher + teacherName;
                }
            }
            System.out.println(teacher);
            courseDOS.get(i).setCourseTeacher(teacher);
        }
        int total;
        total = courseStudentService.countAllCourse(query);
        PageUtils pageUtil = new PageUtils(courseDOS, total);
        return pageUtil;

    }


    @PostMapping("/addCourse")
    @ResponseBody
    R addCourse(@Param("userId") Integer userId,@Param("cid") Integer cid){
        //创建一个CourseStudentDO对象
        CourseStudentDO courseStudentDO = new CourseStudentDO();
        //给CourseStudentDO对象赋值
        courseStudentDO.setCid(cid);
        courseStudentDO.setUserId(userId);
        //将选课的课程id和实训学生id插入课程学生信息表
        if (courseStudentService.insertCourseStudent(courseStudentDO)>0){
            //创建一个CourseScoreDO对象
            CourseScoreDO courseScoreDO = new CourseScoreDO();
            //给CourseScoreDO对象赋值
            courseScoreDO.setCid(cid);
            courseScoreDO.setuserId(userId);
            //将课程id和学生id插入到学生课程成绩表
            courseScoreService.insertCourseScore(courseScoreDO);

            //选课成功之后将此课程的任务加入到correct_task中
            //通过cid查询该课程所有任务
            CourseDO courseDO = courseService.selectById(cid);
            String courseName = courseDO.getCourseName();
            //通过courseName在task_release中查找该课程的所有任务
            List<TaskReleaseDO> taskReleaseDOS = taskReleaseService.selectAllTaskByCourseName(courseName);
            UserDO userDO = userService.selectUserById(userId);
            for (int i=0;i<taskReleaseDOS.size();i++){
                int temp = taskReleaseDOS.get(i).getTid();
                CorrectsTaskDO correctsTaskDO = new CorrectsTaskDO();
                correctsTaskDO.setTid(temp);
                correctsTaskDO.setUserId(userId);
                correctsTaskDO.setEmail(userDO.getEmail());
                correctsTaskDO.setName(userDO.getName());
                correctsTaskDO.setUsername(userDO.getUsername());
                correctsTaskDO.setStudentClass(userDO.getStudentClass());
                correctsTaskService.insertCorrectsTask(correctsTaskDO);
            }
            //操作成功
            return R.ok();
        }else {
            //操作失败
            return R.error();
        }
    }

    @GetMapping("/doCard")
    public String doCard(){
        return "sys/courseStudent/doCard";
    }

    @GetMapping("/listCard")
    @ResponseBody
    PageUtils listCard(@RequestParam Map<String, Object> params) throws Exception{
        UserDO userDO = ShiroUtils.getUser();
        int loginId = Integer.parseInt(Long.toString(userDO.getUserId()));
        params.put("loginId",loginId);
        Query query = new Query(params);
        List<CourseStudentDO> courseStudentDOS = courseStudentService.selectAllCard(params);
        for (int i=0;i<courseStudentDOS.size();i++){
            int cid = courseStudentDOS.get(i).getCid();
            CourseDO courseDO = courseService.selectById(cid);
            courseStudentDOS.get(i).setCourseName(courseDO.getCourseName());
            String time1 = courseDO.getStartDate();
            courseStudentDOS.get(i).setStartDate(time1);
            String time2 = courseDO.getEndDate();
            courseStudentDOS.get(i).setEndDate(time2);
            //如果想比较日期则写成"yyyy-MM-dd"就可以了
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            //将字符串形式的时间转化为Date类型的时间
            //开始时间
            Date a=sdf.parse(time1);
            //结束时间
            Date b=sdf.parse(time2);
            //当前时间
            Date date = new Date();
            String d = sdf.format(date);
            Date c = sdf.parse(d);
            Integer value = DateCompareUtils.isEffectiveDate(c,a,b);
            courseStudentDOS.get(i).setStatus(value);
        }
        int total = courseStudentService.countAllCard(query);
        PageUtils pageUtils = new PageUtils(courseStudentDOS,total);
        return pageUtils;
    }

    @PostMapping("/updateCard")
    @ResponseBody
    R update(Integer id) throws Exception{
        //根据id修改打卡天数及打卡时间
        CourseStudentDO courseStudentDO = courseStudentService.selectById(id);
        int num = courseStudentDO.getCardNum();
        courseStudentDO.setCardNum(num+1);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);
        courseStudentDO.setCardTime(time);
        if (courseStudentService.updateCard(courseStudentDO)>0){
            return R.ok();
        }else {
            return R.error();
        }
    }
}
